<template>
  <section>
  <section class="main isPc">
    <section class="cartEnter">
      <p class="pTitle">
          <router-link tag="a" to="/">首页</router-link> - 
          <router-link tag="a" to="/cart">我的购物车</router-link> - 
          确认订单
        </p>
      <div class="info">
        <div class="left">
          <div class="item">
            <p class="stitle">地址信息</p>
            <!--点击默认地址-->
            <div class="itemInfo" v-for="item in addressData" v-if="addressStart">
              <p class="inputbox">
                <span class="latitle t3">Name:</span>
                <input type="text" @change="wapAddress" placeholder="" v-model="item.first_name" class="intpu03" name="">
              </p>
              <p class="inputbox">
                <span class="latitle t3">Phone Number:</span>
                <input type="text" @change="wapAddress" placeholder="mobile" class="intpu03" v-model="item.mobile" name="">
              </p>
              <p class="inputbox">
                <span class="latitle t3">Address:</span>
                <input type="text" @change="wapAddress" placeholder="address" v-model="item.address" class="intpu03" name="">
              </p>
              <p class="inputbox">
                <span class="latitle t3">Post Code (目前配送范围只限于CF3,CF5,CF10,CF11,CF14,CF23,CF24)</span>
                <input type="text" @change="wapAddress" placeholder="post_code" v-model="item.post_code" class="intpu03" name="">
              </p>
              
              <p class="inputbox">
                <span class="latitle t3">City (目前只限于卡迪夫范围内)</span>
                <input type="text" placeholder="city" value="Cardiff" disabled class="intpu03" name="">
              </p>
              <p class="inputbox">
                <span class="latitle t3">Country</span>
                <input type="text" placeholder="country" value="United Kingdom" disabled class="intpu03" name="">
              </p>
              
            </div>
            <!-- <p class="cartSelect">
              <span class="selectA" @click="closeAddressData">重置</span>
              <span class="selectB" @click="postAddress" >添加地址</span>
            </p> -->
            <p class="allMessage">{{text}}</p>
          </div>
          <div class="item">
            <p class="stitle">备注信息</p>
            <p class="inputbox">
              <textarea v-model="remark" placeholder="Something..."></textarea>
            </p>
          </div>
          <div class="item">
            <p class="stitle">付款方式</p>
            <p class="xtitle pcPayList">统一货到付款<br>现金，微信，支付宝方式都可以<br><img src="/static/images/paylogo.png"></p>
          </div>

          <div class="item">
            <p class="stitle">送货时间</p>
            <p class="inputbox addList">
              <label v-for="item in payList">
                <input name="Fruit" type="radio" v-model="payListId" @click="payTime(item.id)" :value="item.id" />{{item.type_name}}
              </label>
            </p>
          </div>

          <button @click="postOrder">确认提交</button>
        </div>
        <div class="right">
          <div class="item">
            <p class="stitle">商品清单</p>
            <div class="cartPrc">
              <ul>
                <li v-for="item in List">
                    <div class="img">
                      <router-link :to="'prcShow?id='+item.goods_id"><img :src="ksrc+item.goods_logo"></router-link>
                    </div>
                    <div class="name">
                      <router-link :to="'prcShow?id='+item.goods_id">{{item.goods_name}}</router-link>
                      <br>£{{item.goods_price|allPrice}}
                    </div>
                    <div class="num">
                      <p class="price">
                        <!-- <input type="text" readonly="readonly" :value="item.goods_count" name=""> -->
                        <input type="number" @change="change(item)" min="0" v-model="item.goods_count" name="">
                      </p>
                      <p class="price">£{{item.amount|allPrice}}</p>
                      <p><span class="close" @click="delPrc(item.id)"></span></p>
                    </div>
                </li>
              </ul>
            </div>
            <div class="cartNum">
              <input type="text" class="youhui" name="" placeholder="输入优惠码...">
              <button >确定</button>
            </div>

            <div v-if="vipRatio!=100">
                <div class="cartCount">
                      <p>总价1<span>£{{allPrice|allPrice}}</span></p>
                      <p>运费<span>£0.00</span></p>
                      <p>优惠<span>{{vipRatio|aa}}折</span></p>
                    </div>
                    <p class="cartAll">合计<span>£{{vipPrice}}</span></p>
                </div>
            </div>
            <div v-if="vipRatio==100">
                  <div v-if="youStart" >
                    <div class="cartCount">
                      <p>总价<span>£{{allPrice|allPrice}}</span></p>
                      <p>运费<span>£0.00</span></p>
                      <p v-if="cartPrice.ratio==100">优惠<span v-if="cartPrice"></span></p>
                      <p v-if="cartPrice.ratio!=100">优惠<span v-if="cartPrice">{{cartPrice.ratio|aa}}折</span></p>
                    </div>
                    <p class="cartAll">合计<span v-if="cartPrice">£{{payPrice|allPrice}}</span></p>
                  </div>
                  
                  <div v-if="!youStart">
                      <div class="cartCount">
                        <p>总价<span>£{{allPrice|allPrice}}</span></p>
                        <p>运费<span>£0.00</span></p>
                        <p>优惠<span>0.00</span></p>
                      </div>
                      <p class="cartAll">合计<span v-if="cartPrice">£{{allPrice|allPrice}}</span></p>
                  </div>
            </div>
            
          </div>
        </div>
      </div>
    </section>
  </section>
  <!--手机-->
  <section class="mainWap isWap">
    <div class="cartEntWap">
        <div class="item" :class="{'on':wapCartStauts.A}">
            <p class="stitle" @click="wapGetA">地址信息<span class="on"></span></p>
            <!--点击默认地址-->
            <div class="itemInfo wapNone" v-for="item in addressData" v-if="addressStart">
              <p class="inputbox">
                <span class="latitle t3">Name</span>
                <input type="text" @change="wapAddress" placeholder="" v-model="item.first_name" class="intpu03" name="">
              </p>
              <p class="inputbox">
                <span class="latitle t3">Phone Number</span>
                <input type="text" @change="wapAddress" placeholder="" class="intpu03" v-model="item.mobile" name="">
              </p>
              <p class="inputbox">
                <span class="latitle t3">Address</span>
                <input type="text" @change="wapAddress" placeholder="请详细填写" v-model="item.address" class="intpu03" name="">
              </p>

              <p class="inputbox">
                <span class="latitle t3">City</span>
                <span class="wapCartP">Cardiff</span>
              </p>
              <p class="inputbox">
                <span class="latitle t3">Country</span>
                <span class="wapCartP">United Kingdom</span>
              </p>
              <p class="inputbox">
                <span class="latitle t3">Post Code</span>
                <input type="text" @change="wapAddress" placeholder="post_code" v-model="item.post_code" class="intpu03" name="">
              </p>
              
              <!-- <p class="cartSelect">
                <span class="selectA" @click="closeAddressData">重置</span>
              </p> -->
              <p class="allMessage">{{text}}</p>
            
            </div>
            
          </div>
          <div class="item" :class="{'on':wapCartStauts.B}">
            <p class="stitle" @click="wapGetB">备注信息<span class="on"></span></p>
            <p class="inputbox wapNone">
              <textarea v-model="remark" placeholder="Something..."></textarea>
            </p>
          </div>
          <div class="item" :class="{'on':wapCartStauts.C}">
            <p class="stitle" @click="wapGetC">付款方式<span class="on"></span></p>
            <p class="xtitle wapNone">统一货到付款<br>现金，微信，支付宝方式都可以<br><img src="/static/images/paylogo.png"></p>
          </div>

          <div class="item" :class="{'on':wapCartStauts.D}">
            <p class="stitle" @click="wapGetD">送货时间<span class="on"></span></p>
            <p class="inputbox addList wapNone">
              <label v-for="item in payList">
                <input name="Fruit" type="radio" v-model="payListId" @click="payTime(item.id)" :value="item.id" />{{item.type_name}}
              </label>
            </p>
          </div>

          
          <div class="item">
            <p class="stitle">商品清单</p>
            <div class="cartPrc">
              <ul>
                <li v-for="item in List">
                    <div class="img">
                      <router-link :to="'prcShow?id='+item.goods_id"><img :src="ksrc+item.goods_logo"></router-link>
                    </div>
                    <div class="name">
                      <router-link :to="'prcShow?id='+item.goods_id">{{item.goods_name}}</router-link>
                    </div>
                    <div class="num">
                      <p class="price">£{{item.amount|allPrice}}</p>
                      <p class="price">
                        <!-- <input type="text" readonly="readonly" :value="item.goods_count" name=""> -->
                        <input type="number" @change="change(item)" min="0" v-model="item.goods_count" name="">
                      </p>
                      
                      <p><span class="close" @click="delPrc(item.id)"></span></p>
                    </div>
                </li>
              </ul>
            </div>
            <div class="cartNum">
              <input type="text" class="youhui" name="" placeholder="输入优惠码...">
              <button >确定</button>
            </div>

            <div v-if="vipRatio!=100">
                <div class="cartCount">
                      <p>总价1<span>£{{allPrice|allPrice}}</span></p>
                      <p>运费<span>£0.00</span></p>
                      <p>优惠<span>{{vipRatio|aa}}折</span></p>
                    </div>
                    <p class="cartAll">合计<span>£{{vipPrice}}</span></p>
                </div>
            </div>
            <div v-if="vipRatio==100">
                  <div v-if="youStart" >
                    <div class="cartCount">
                      <p>总价<span>£{{allPrice|allPrice}}</span></p>
                      <p>运费<span>£0.00</span></p>
                      <p v-if="cartPrice.ratio==100">优惠<span v-if="cartPrice"></span></p>
                      <p v-if="cartPrice.ratio!=100">优惠<span v-if="cartPrice">{{cartPrice.ratio|aa}}折</span></p>
                    </div>
                    <p class="cartAll">合计<span v-if="cartPrice">£{{payPrice|allPrice}}</span></p>
                  </div>
                  
                  <div v-if="!youStart">
                      <div class="cartCount">
                        <p>总价<span>£{{allPrice|allPrice}}</span></p>
                        <p>运费<span>£0.00</span></p>
                        <p>优惠<span>0.00</span></p>
                      </div>
                      <p class="cartAll">合计<span v-if="cartPrice">£{{allPrice|allPrice}}</span></p>
                  </div>
            </div>
          </div>
          
          <div class="wapBox">
            <button @click="postOrderWap">确定提交订单</button>
            <button>取消</button>
          </div>
          


    </div>
  </section>
</section>
</template>
<script>
import axios from 'axios'
import {Get,Post,Delete,Put} from '@/config/api.js'
export default {
  name: 'cart',
  data() {
    return {
      tableStart:false,//表单状态
      addStart:false,//有没有收货地址
      gShow: false, //购物车是否有商品
      allClick: false, //是否全选
      loadStart: false,
      addressStart:false,//点击显示默认地址
      addressId:'',//默认地址id
      text:'',//提示文字
      List: [],
      getList: [],
      addressData:[],//用户地址信息
      addressList:[],//后台送货地区
      payList:[],//送货方式
      payListId:4,
      ksrc: 'http://oub2urxei.bkt.clouddn.com/',
      goodsId: '',
      youHui:[],//优惠列表
      cartPrice:'',//优惠名称
      youStart:false,//优惠比例
      youPay:'',//优惠比例
      remark:'',
      vipRatio:'',//vip优惠
      putAddress:{
        A:'',//详细地址
        B:'',//自己写的地址
        C:'',//邮编
        mobile:'',
        firstname:'',
        lastname:'',
        is_default:1
      },
      wapCartStauts:{
        A:true,
        B:false,
        C:false,
        D:true
      },
      wapAddressStauts:false
    }
  },
  created() {
    this.$store.dispatch("isLoading",false)
  },
  filters:{
    aa(val){
      return val/10
    },
    vipPrice(val){
      let pay=(vipRatio*val)/100
      let arr=pay.toString().split(".")
      if(arr.length>1){
        let len=arr[1].length
        if(len==1){
          return pay+'0'
        }else{
          return pay
        }
      }else{
        return pay+'.00'
      }
    }
  },
  mounted() {
    this.vLogin()
    this.getData()//获取购物车信息
    this.getPay()//获取后台设置的送货方式
    this.getAddressData()//获取用户默认地址
    this.getMe()
    this.$store.dispatch("isLoading",true)

  },
  computed: {
    //商品
    prcArr: function() {
      let num=[];
      for (var i = 0; i < this.List.length; i++) {
        num.push(parseInt(this.List[i].goods_id))
      }
      return num
    },
    //商品数量
    numArr: function() {
      let num=[];
      for (var i = 0; i < this.List.length; i++) {
        num.push(parseInt(this.List[i].goods_count))
      }
      return num
    },
    //商品购物车id
    cartArr: function() {
      let num=[];
      for (var i = 0; i < this.List.length; i++) {
        num.push(parseInt(this.List[i].id))
      }
      return num
    },
    //商品总价格
    allPrice: function() {
      let num=0;
      for (var i = 0; i < this.List.length; i++) {
        num+=this.List[i].amount
      }
      return num.toFixed(2)
    },
    //商品
    addressPost: function() {
      if(this.addressId!=''){
        return true
      }else{
        return false
      }
    },
    payPrice:function(){
      return (this.allPrice*this.cartPrice.ratio/100).toFixed(2)
    },
    //vip价格
    vipPrice:function(){
      return (this.allPrice*this.vipRatio/100).toFixed(2)
    },

    //检测表单
    fNameCheck(){
      return this.Input(this.putAddress.firstname)
    },
    lNameCheck(){
      return this.Input(this.putAddress.lastname)
    },
    ACheck(){
      return this.Input(this.putAddress.A)
    },
    BCheck(){
      return this.Input(this.putAddress.B)
    },
    CCheck(){
      return this.Input(this.putAddress.C)
    },
    mobileCheck(){
      return this.InputTel(this.putAddress.mobile)
    },
    addAllCheck(){
      if(this.fNameCheck&&this.lNameCheck&&this.mobileCheck&&this.ACheck&&this.BCheck&&this.CCheck){
        return true
      }else{
        return false
      }
    }
  },
  methods: {
    //送货时间
    payTime(val){
      this.payListId=val
    },
    //清空收货地址
    closeAddressData(){
      for(var key in this.addressData[0]){
        this.addressData[0][key]=''
      }
    },
    postNewaddress(){
      if(this.addAllCheck){
        this.addStart=true
        this.postAddress()
      }else{
        this.tableStart=true
        this.text="请填写收货信息"
      }
    },

    //确定下单
    async postOrder() {
      let that=this
      if(this.wapAddressStauts==true){
        await this.postAddress()

        let that=this
        let data={
          "goods_ids":this.prcArr,
          "goods_counts":this.numArr,
          "address_id":this.addressId,
          "remark":this.remark,
          "pay_type_id":this.payListId
        }
        let status=1
        this.$store.dispatch("isLoading",true)
        await Post('/order',this.$store.state.token,data).then(function(reg){
            status=2
        }).catch(function(err){
          alert(err.data.message)
        })

        if(status==2){
          await Delete('/carts/'+this.cartArr,this.$store.state.token).then(function(reg){
            that.$router.push('/orderList')
          }).catch(function(err){
            alert(err.data.message)
          })
        }
        
        this.$store.dispatch("isLoading",false)
                
      }else{
          if(this.addressId!=''){
                let that=this
                let data={
                  "goods_ids":this.prcArr,
                  "goods_counts":this.numArr,
                  "address_id":this.addressId,
                  "remark":this.remark,
                  "pay_type_id":this.payListId
                }
                let status=1
                this.$store.dispatch("isLoading",true)
                await Post('/order',this.$store.state.token,data).then(function(reg){
                    status=2
                }).catch(function(err){
                  alert(err.data.message)
                })

                if(status==2){
                  await Delete('/carts/'+this.cartArr,this.$store.state.token).then(function(reg){
                    that.$router.push('/orderList')
                  }).catch(function(err){
                    alert(err.data.message)
                  })
                }
                
                this.$store.dispatch("isLoading",false)
          }else{
            this.postNewaddress()
          }
      }
      
    },
    //获取送货方式
    async getPay(){
      let reg=await Get('/order/pay/type?_sort=id',this.$store.state.token)
      this.payList=reg.data
    },
    //获取购物车
    async getData(){
      let that=this
      let kk=0
      await Get('/carts?_sort=id&_pagination=false',this.$store.state.token).then(function(reg){
        that.List=reg.data
        for(let i=0;i<reg.data.length;i++){
          kk+=reg.data[i].amount
        }
      }).then(function(){
        that.getYouhui(kk)
      })
      
    },
    //获取优惠信息
    async getYouhui(val){
      let reg=await Get('/order/buy/'+val,this.$store.state.token)
      if(reg.best!=null){
        this.youStart=true
      }else{
        this.youStart=false
      }
      this.cartPrice=reg.best
    },
    //获取用户信息
    async getMe(){
      let reg=await Get('/users/me',this.$store.state.token)
      this.vipRatio=reg.data.vip_ratio
    },
    //获取用户收货地址
    async getAddressData(){
        if(this.vLogin()){
          let reg=await Get('/users/address?is_default=1',this.$store.state.token)
          if(reg.data.length!=0){
            this.addressStart=true
            this.addressData=reg.data
            this.addressId=reg.data[0].id
            this.text=''
          }else{
            this.text="没有默认地址"
          }
          this.$store.dispatch("isLoading",false)
        }
    },
    //添加收货地址
    async postAddress(){
          let data={
            "address":this.addressData[0].address,
            "state":this.addressData[0].state,
            "post_code":this.addressData[0].post_code,
            "mobile":this.addressData[0].mobile,
            "first_name":this.addressData[0].first_name,
            "last_name":this.addressData[0].firstname,
            "is_default":1
          }
          this.$store.dispatch("isLoading",true)
          let that=this
          await Post('/users/address',this.$store.state.token,data).then(function(reg){
            this.addressId=reg.data.id
            this.text="设置为默认地址成功"
            this.$store.dispatch("isLoading",false)
            setTimeout(function(){
              that.getAddressData()
            },300)
            
          }.bind(this)).catch(function(err){
            alert(err.data.message)
          })
          
          /*if(this.addStart){
            this.postOrder()
          }else{
            this.text="设置为默认地址成功"
          }*/
      },
    //删除商品
    async delPrc(e){
        let reg=await Delete('/carts/'+e,this.$store.state.token)
        alert('删除成功')
        this.getData()
    },
    //修改商品数量
    async change(e){
      if(this.vLogin()){
          this.$store.dispatch("isLoading",true)
          if(e.goods_count!=0){
            let data={
              "goods_count":e.goods_count
            }
            let reg=await Put('/carts/'+e.id,this.$store.state.token,data)
          }else{
            let reg=await Delete('/carts/'+e.id,this.$store.state.token)
          }
          this.getData()
          this.$store.dispatch("isLoading",false)
        }
    },
    //关闭登录窗
    closeLogin() {
      this.$router.push({ path: '/home' })
    },
    //确定下单
    async postOrderWap() {
      let that=this
      if(this.wapAddressStauts==true){
        await this.postAddress()
        let data={
          "goods_ids":this.prcArr,
          "goods_counts":this.numArr,
          "address_id":this.addressId,
          "remark":this.remark,
          "pay_type_id":this.payListId
        }
        let status=1
        this.$store.dispatch("isLoading",true)
        await Post('/order',this.$store.state.token,data).then(function(reg){
            status=2
        }).catch(function(err){
          alert(err.data.message)
        })

        if(status==2){
          await Delete('/carts/'+this.cartArr,this.$store.state.token).then(function(reg){
            that.$router.push('/cartSuccess')
          }).catch(function(err){
            alert(err.data.message)
          })
        }
        this.$store.dispatch("isLoading",false)
        this.getNowWap()
      }else{
        if(this.addressId!=''){
            let that=this
            let data={
              "goods_ids":this.prcArr,
              "goods_counts":this.numArr,
              "address_id":this.addressId,
              "remark":this.remark,
              "pay_type_id":this.payListId
            }
            let status=1
            this.$store.dispatch("isLoading",true)
            await Post('/order',this.$store.state.token,data).then(function(reg){
                status=2
            }).catch(function(err){
              alert(err.data.message)
            })

            if(status==2){
              await Delete('/carts/'+this.cartArr,this.$store.state.token).then(function(reg){
                that.$router.push('/cartSuccess')
              }).catch(function(err){
                alert(err.data.message)
              })
            }
            
            this.$store.dispatch("isLoading",false)
            this.getNowWap()
        }else{
          this.postNewaddress()
        }
      }
      
    },
    wapGetA(){
      if(this.wapCartStauts.A==true){
        this.wapCartStauts.A=false
      }else{
        this.wapCartStauts.A=true
      }
    },
    wapGetB(){
      if(this.wapCartStauts.B==true){
        this.wapCartStauts.B=false
      }else{
        this.wapCartStauts.B=true
      }
    },
    wapGetC(){
      if(this.wapCartStauts.C==true){
        this.wapCartStauts.C=false
      }else{
        this.wapCartStauts.C=true
      }
    },
    wapGetD(){
      if(this.wapCartStauts.D==true){
        this.wapCartStauts.D=false
      }else{
        this.wapCartStauts.D=true
      }
    },
    //收货地址改变了
    wapAddress(){
      this.wapAddressStauts=true
    },
    //更新购物车信息
    async getNowWap(){
      let reg=await Get('/carts?_sort=id&_pagination=false',this.$store.state.token)
        let all=0
        for(let i=0;i<reg.data.length;i++){
          all+=reg.data[i].amount
        }
        let data={
          num:reg.data.length,
          price:all
        }
        this.$store.dispatch("wapCart",data)
    }
  }
}

</script>
